package com.moss.cloud.common.webflux.filter;

import com.moss.cloud.auth.api.utils.JwtAccessToken;
import com.moss.cloud.common.core.constant.Constant;
import com.moss.cloud.common.core.model.vo.AuthUser;
import com.moss.cloud.common.core.utils.AuthUserUtil;
import com.moss.cloud.common.core.utils.UserContextHolder;
import com.moss.cloud.common.core.utils.WebFluxUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

@Slf4j
@Component
public class WebFluxUserInterceptor implements WebFilter {
    private static final String AUTHORIZATION = "Authorization";

    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String authentication = request.getHeaders().getFirst(AUTHORIZATION);
        String userInfoString = StringUtils.defaultIfBlank(authentication, Constant.NO_LOGIN);
        if (StringUtils.isNotEmpty(userInfoString) && !userInfoString.equals(Constant.NO_LOGIN)) {
            AuthUser authUser = AuthUserUtil.preAuthUser(JwtAccessToken.getJwt(userInfoString).getClaims());
            log.info("当前登录用户:{}", authUser.getUserName());
            UserContextHolder.setUserInfo(authUser);
            return chain.filter(exchange).doFinally(signalType -> UserContextHolder.clear());
        }
        return unauthorized(exchange);
    }

    /**
     * 拒绝，返回401
     *
     * @param serverWebExchange
     * @return
     */
    private Mono<Void> unauthorized(ServerWebExchange serverWebExchange) {
        return WebFluxUtil.unauthorized(serverWebExchange);
    }
}
